package com.mr.security.web.commons.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * Class: WebSocket
 * User (作者):MRui
 * TODO (描述)：webSocket
 * Date 2018.10.04 21:58
 */
@Component
@Slf4j
@ServerEndpoint("/webSocket")
public class WebSocket {

    private Session session;

    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();

    /**
    * User (作者): MRui
    * TODO (描述)：打开连接（有新消息）
    * Data：2018.10.04 22:05
    */
    @OnOpen
    public void opOpen(Session session){
        this.session = session;
        webSockets.add(this);
        log.info("[webSocket消息] 有新的连接，总数：{}",webSockets.size());
    }

    /**
    * User (作者): MRui
    * TODO (描述)：关闭连接
    * Data：2018.10.04 22:05
    */
    @OnClose
    public void onClose(){
        webSockets.remove(this);
        log.info("[webSocket消息] 断开连接，总数：{}",webSockets.size());
    }

    /**
    * User (作者): MRui
    * TODO (描述)：收到消息
    * Data：2018.10.04 22:04
    */
    @OnMessage
    public void onMessage(String message){
        log.info("[webSocket消息] 收到客户端发来的消息：{}",message);
    }

    /**
    * User (作者): MRui
    * TODO (描述)：（调用）设置消息
    * Data：2018.10.04 22:13
    */
    public void sendMessage(String message){
        try {
            for (WebSocket webSocket : webSockets){
                log.info("[webSocket消息] 广播消息，message={}",message);
                webSocket.session.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
